const jwt = require('jsonwebtoken')
// 响应信息的函数
function resinfo(res, errorCode, message, data = null) {
    res.json({
        errorCode,
        message,
        data
    })
}
//令牌的中间键
function checkToken(req, res, next) {
    let responseObj = {
        errorCode: 0,
        msg: '成功'
    }
    let token = req.headers.authorization
    // 判断是否携带
    if(!token) {
        responseObj.errorCode = 401
        responseObj.msg = '令牌缺失'
        res.json(responseObj)
        return
    } else {
        // 验证令牌是否正确/是否有效
        let decodeObj
        try{
            decodeObj = jwt.verify(token, 'ZB&&LXX&&CSJ&&ZLF&&ZWC&&YYZ&&CKN&&CDY')
            console.log();
            // 验证是否有效
            if(decodeObj.startTime + decodeObj.expires <= +new Date()) {
                responseObj.errorCode = 405
                responseObj.msg = '令牌过期'
                res.json(responseObj)
                return
            }  else {
                next()
            }
        } catch(err) {
            console.log(err);
            responseObj.errorCode = 402
            responseObj.msg = '令牌错误'
            res.json(responseObj)
            return
        }
        //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZSI6MTUzNTM0MDIwNDcsInN0YXJ0VGltZSI6MTY2OTczNjMyNjAxMywiZXhwaXJlcyI6NzIwMDAwMCwiaWF0IjoxNjY5NzM2MzI2fQ.w80eVaTGOLdrL41nGs99oPxcaypCB3Ss7dl2Cxgd-VA
       
    }
}

module.exports = {
    resinfo,
    checkToken
}
